// pages/login/login.js
const utilbase = require('../../utils/setpwdbase64');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showModal: false, //注册弹窗
    denglphone: '', //登录电话
    denglpasswd: '', //登录密码
    // denglphone: '18338729019', //登录电话
    // denglphone: '18600013182', //登录电话
    // denglphone: '15617896709', //登录电话
    // denglphone: '15738316187', //登录电话
    // denglpasswd: '12345678', //登录密码
    // denglpasswd: 'mnbvcxz', //登录密码
    zhucphone: '', //注册电话
    zhucyanzm: '', //注册验证码
    zhucpasswd1: '', //注册密码1
    zhucpasswd2: '', //注册密码2
    yzmTime: 60,
    redmsg: false,
    userSig:'',
    ispassword:'password',
  },
 
  // 协议是否已读
  redmsg() {
    let that = this
    // console.log(e.detail.value)
    that.setData({
      redmsg: !that.data.redmsg
    })
  },

  toxieyi(e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/setting/page/xieyi/xieyi?flag=' + e.currentTarget.dataset.index,
    })
  },

  // 登录电话
  dlphone(e) {
    let that = this
    that.setData({
      denglphone: e.detail.value
    })
  },

  // 登录密码
  dlpasswd(e) {
    let that = this
    that.setData({
      denglpasswd: e.detail.value.replace(/(^\s*)|(\s*$)/g, "")
    })
  },

  // 注册电话
  zcphone(e) {
    let that = this
    that.setData({
      zhucphone: e.detail.value
    })
  },

  // 发送验证码
  fasongyzm() {
    let that = this
    var telStr = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
    var inputStr = that.data.zhucphone
    if (!(telStr.test(inputStr))) {
      wx.showToast({
        title: '手机号码输入不规范',
        icon: 'none',
        duration: 1500
      })
      return
    }
    // setTimeout(function() {
    //   wx.showLoading({
    //     title: '加载中',
    //     mask: true
    //   })
    // }, 0)
    that.setData({
      yzmTime: 59
    })
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "phoneMSCode",
        userPhone: that.data.zhucphone
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        console.log(res)
        setTimeout(function() {
          wx.hideLoading()
        }, 0)
        setTimeout(function() {
          wx.showToast({
            title: res.data.resultNote,
            icon: 'none',
            duration: 1500
          })
        }, 0)
      }
    });
    var interval = setInterval(function timestampToTime() {
      var date = that.data.yzmTime
      if (date <= 1) {
        that.setData({
          yzmTime: 60
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 0)
        clearInterval(interval)
      } else {
        date--
        that.setData({
          yzmTime: date
        })
        // console.log(date)
      }
    }, 1000);
  },

  // 注册验证码
  zcyanzm(e) {
    let that = this
    that.setData({
      zhucyanzm: e.detail.value
    })
  },

  // 注册密码1
  zcmima1(e) {
    let that = this;
    var value = e.detail.value;
    
    that.setData({
      zhucpasswd1: e.detail.value.replace(/(^\s*)|(\s*$)/g, "")
    })
  },
  onblur1(e) {
    let that = this;
    var value = e.detail.value;
    console.log(value.length)
    // if (value.length >= 8 || value.length <= 16) {
      
    //   that.setData({
    //     zhucpasswd1: e.detail.value.replace(/(^\s*)|(\s*$)/g, "")
    //   })
      
    // } else {
    //   value = ''
    //   console.log('8~16')
    //   wx.showToast({
    //     title: '密码在8~16位之间',
    //     icon: 'none'
    //   })
    //   that.setData({
    //     zhucpasswd1: value,
    //     ispassword: false
    //   })
    // }
    // console.log(this.data.zhucpasswd1)
  },

  // 注册密码2
  zcmima2(e) {
    let that = this
    that.setData({
      zhucpasswd2: e.detail.value.replace(/(^\s*)|(\s*$)/g, "")
    })
  },
  onblur2(e) {
    let that = this;
    let value = e.detail.value.toString();
    console.log(value.length)
    // if (value.length < 8 || value.length > 16) {
    //   console.log('8~16')
    //   wx.showToast({
    //     title: '密码在8~16位之间',
    //     icon: 'none'
    //   })
    //   that.setData({
    //     zhucpasswd2: ''
    //   })
    // } else {
    //   that.setData({
    //     zhucpasswd2: e.detail.value.replace(/(^\s*)|(\s*$)/g, "")
    //   })
    // }
    // console.log(this.data.zhucpasswd2)
  },

  // 忘记密码
  forget() {
    wx.navigateTo({
      url: '/pages/setting/page/wangjimima/wangjimima',
      // 实验协议
      // url: '/pages/setting/page/xieyi/xieyi',

    })
  },

  // 去注册2界面
  zhucetwo() {
    let that = this
    var telStr = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
    var inputStr = that.data.zhucphone
    if (!(telStr.test(inputStr))) {
      wx.showToast({
        title: '手机号码输入不规范',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!that.data.zhucyanzm) {
      wx.showToast({
        title: '验证码不能为空',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (that.data.zhucpasswd1.length < 6 || that.data.zhucpasswd1.length >16){
      wx.showToast({
        title: '密码不能少于6位',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (that.data.zhucpasswd1 != that.data.zhucpasswd2) {
      wx.showToast({
        title: '两次输入的密码不一致',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!that.data.zhucpasswd1) {
      wx.showToast({
        title: '密码不能为空',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!that.data.redmsg) {
      setTimeout(function() {
        wx.showToast({
          title: '请阅读并同意协议',
          icon: 'none'
        })
      }, 0)
      return
    }
    setTimeout(function() {
      wx.showLoading({
        title: '正在提交',
      })
    }, 0)
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    console.log("当前时间戳为：" + timestamp);
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "setUserInfo",
        loginName: that.data.zhucphone,
        smsCode: that.data.zhucyanzm,
        password: utilbase.base64encode(utilbase.utf16to8(that.data.zhucpasswd1)),
        tpassword: utilbase.base64encode(utilbase.utf16to8(that.data.zhucpasswd2)),
        unicode: timestamp
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        setTimeout(function() {
          wx.hideLoading()
        }, 0)
        setTimeout(function() {
          wx.showToast({
            title: res.data.resultNote,
            icon: 'none',
            duration: 2000
          })
        }, 0)
        console.log(res)
        if (res.data.result == 1) {
          return
        } else {
          wx.setStorageSync("token", res.data.token);
          wx.setStorageSync("denglphone", that.data.zhucphone);
          wx.setStorageSync("password", utilbase.base64encode(utilbase.utf16to8(that.data.zhucpasswd2)));
          setTimeout(function() {
            wx.navigateTo({
              url: '/pages/setting/page/zhuce/zhuce?userid=' + res.data.userId,
            })
          }, 1500)
        }
      },
      fail(err) {
        setTimeout(function () {
          wx.hideLoading()
          wx.stopPullDownRefresh() //停止下拉刷新
        }, 0)
        setTimeout(function () {
          wx.showToast({
            title: '网络错误，稍后重试',
            icon: 'none',
            duration: 1500
          })
        }, 0)
      }
    });
  },

  // 去首页界面
  todenglu() {
    let that = this
    var telStr = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
    var inputStr = that.data.denglphone
    if (!(telStr.test(inputStr))) {
      wx.showToast({
        title: '手机号码输入不规范',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!that.data.denglpasswd) {
      wx.showToast({
        title: '密码不能为空',
        icon: 'none',
        duration: 2000
      })
      return
    }
    setTimeout(function() {
      wx.showLoading({
        title: '登录中',
      })
    }, 0)
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    console.log("当前时间戳为：" + timestamp);
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "merlogin",
        userName: that.data.denglphone,
        password: utilbase.base64encode(utilbase.utf16to8(that.data.denglpasswd)),
        // password: that.data.denglpasswd,
        malltype: 2,
        unicode: timestamp
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        console.log(res)
        setTimeout(function() {
          wx.hideLoading()
        }, 0)
        setTimeout(function() {
          wx.showToast({
            title: res.data.resultNote,
            icon: 'none',
            duration: 2000
          })
        }, 0)
        if (res.data.result == 1) {
          return
        } else {
          wx.setStorageSync("denglphone", that.data.denglphone);
          wx.setStorageSync("password", utilbase.base64encode(utilbase.utf16to8(that.data.denglpasswd)));
          wx.setStorageSync("userId", res.data.userId);
          wx.setStorageSync("shopId", res.data.shopId);
          wx.setStorageSync("phone", res.data.phone);
          wx.setStorageSync("userName", res.data.userName);
          wx.setStorageSync("token", res.data.token);
          let userId=res.data.userId
          if(userId != ''){
            wx.request({
              url: app.globalData.myurl, //自己的服务接口地址
              method: "post",
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              data: {
                cmd: 'updateUserSig',
                userId: wx.getStorageSync('userId')
              },
              success: function success(ress) {
                console.log(ress);
                if (ress.data.result == 1) {
                  wx.showToast({
                    title: ress.data.resultNote,
                    icon:"none",
                    duration:1500
                  })
                } else {
                  // wx.setStorageSync("rctoken", rctoken);
                  wx.setStorageSync('userSig', ress.data.userSig)
                }
        
        
              }
            });
          }
          app.globalData.myphones = that.data.denglphone;

          if (res.data.isNInfo == 0 || res.data.checkstate == 2) {
            setTimeout(function() {
              wx.navigateTo({
                url: '/pages/setting/page/zhuce/zhuce?userid=' + res.data.userId,
              })
            }, 1500)
          } else {
            setTimeout(function() {
              wx.switchTab({
                url: '/pages/tabBar/index/index',
              })
            }, 1500)
          }
        }
      },
      fail(err) {
        setTimeout(function () {
          wx.hideLoading()
          wx.stopPullDownRefresh() //停止下拉刷新
        }, 0)
        setTimeout(function () {
          wx.showToast({
            title: '网络错误，稍后重试',
            icon: 'none',
            duration: 1500
          })
        }, 0)
      }
    });
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    if (wx.getStorageSync('shopId') && wx.getStorageSync('userId') && wx.getStorageSync('telephone')) {
      setTimeout(function () {
        wx.showLoading({
          title: '登录中',
        })
      }, 0)
      var timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000;
      console.log("当前时间戳为：" + timestamp);
      wx.request({
        url: app.globalData.myurl,
        data: {
          cmd: "merlogin",
          userName: wx.getStorageSync('denglphone'),
          password: wx.getStorageSync('password'),
          // password: that.data.denglpasswd,
          malltype: 2,
          unicode: timestamp
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success(res) {
          console.log(res)
          setTimeout(function () {
            wx.hideLoading()
          }, 0)
          setTimeout(function () {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 2000
            })
          }, 0)
          if (res.data.result == 1) {
            return
          } else {
            wx.setStorageSync("userId", res.data.userId);
            // wx.setStorageSync("userSig", res.data.userSig);
            wx.setStorageSync("shopId", res.data.shopId);
            wx.setStorageSync("phone", res.data.phone);
            wx.setStorageSync("userName", res.data.userName);
            wx.setStorageSync("token", res.data.token);
            let userSig=res.data.userSig
          if(userSig == ''){
            console.log("12345678984687845")
            wx.request({
              url: app.globalData.url, //自己的服务接口地址
              method: "post",
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              data: {
                cmd: 'updateUserSig',
                userId: wx.getStorageSync('userId')
              },
              success: function success(ress) {
                console.log(ress);
                if (ress.data.result == 1) {
                  wx.showToast({
                    title: ress.data.resultNote,
                    icon:"none",
                    duration:1500
                  })
                } else {
                  // wx.setStorageSync("rctoken", rctoken);
                  wx.setStorageSync('userSig', ress.data.userSig)
                }
        
        
              }
            });
          }
            app.globalData.myphones = wx.getStorageSync('denglphone');
            if (res.data.isNInfo == 0 || res.data.checkstate == 2) {
              setTimeout(function () {
                wx.navigateTo({
                  url: '/pages/setting/page/zhuce/zhuce?userid=' + res.data.userId,
                })
              }, 1500)
            } else {
              setTimeout(function () {
                wx.switchTab({
                  url: '/pages/tabBar/index/index',
                })
              }, 1500)
            }
          }
        },
        fail(err) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showToast({
              title: '网络错误，稍后重试',
              icon: 'none',
              duration: 1500
            })
          }, 0)
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      // denglphone: app.globalData.myphones
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // 注册弹窗
  tozhuce: function() {
    this.setData({
      showModal: true
    })
  },
  preventTouchMove: function() {

  },


  close_mask: function() {
    this.setData({
      showModal: false
    })
  },





})